import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class HelpDocsPage extends StatefulWidget {
  @override
  _HelpDocsPageState createState() => _HelpDocsPageState();
}

class _HelpDocsPageState extends State<HelpDocsPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('帮助文档'),
        backgroundColor: Theme.of(context).colorScheme.surface,
        elevation: 0,
        bottom: TabBar(
          controller: _tabController,
          tabs: [
            Tab(icon: Icon(Icons.help_outline), text: '快速开始'),
            Tab(icon: Icon(Icons.settings), text: '参数说明'),
            Tab(icon: Icon(Icons.code), text: '使用示例'),
            Tab(icon: Icon(Icons.tips_and_updates), text: '最佳实践'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildQuickStartTab(),
          _buildParametersTab(),
          _buildExamplesTab(),
          _buildBestPracticesTab(),
        ],
      ),
    );
  }

  Widget _buildQuickStartTab() {
    return SingleChildScrollView(
      controller: _scrollController,
      padding: EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionCard(
            '欢迎使用 Nuitka 构建工具',
            '这是一个基于 Flutter 开发的 Python Nuitka 桌面构建工具，帮助您轻松将 Python 项目编译为原生可执行文件。',
            Icons.rocket_launch,
            Colors.blue,
          ),
          SizedBox(height: 16),
          _buildSectionCard(
            '什么是 Nuitka？',
            'Nuitka 是一个 Python 编译器，它将 Python 代码编译为 C++ 代码，然后编译为机器码，从而获得更好的性能和独立的可执行文件。',
            Icons.speed,
            Colors.green,
          ),
          SizedBox(height: 16),
          _buildStepsCard(),
          SizedBox(height: 16),
          _buildRequirementsCard(),
        ],
      ),
    );
  }

  Widget _buildStepsCard() {
    return Card(
      elevation: 2,
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Colors.orange, Colors.deepOrange],
                    ),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(Icons.list_alt, color: Colors.white, size: 20),
                ),
                SizedBox(width: 12),
                Text(
                  '快速开始步骤',
                  style: Theme.of(
                    context,
                  ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
                ),
              ],
            ),
            SizedBox(height: 16),
            _buildStep(1, '项目配置', '在"项目配置"页面选择您的 Python 文件和输出目录'),
            _buildStep(2, '构建设置', '配置构建模式、优化级别和依赖项'),
            _buildStep(3, 'AI 建议', '使用 AI 构建建议获取最佳配置推荐'),
            _buildStep(4, '开始构建', '在构建监控页面启动构建过程'),
            _buildStep(5, '完成', '等待构建完成，获取可执行文件'),
          ],
        ),
      ),
    );
  }

  Widget _buildStep(int number, String title, String description) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 24,
            height: 24,
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              shape: BoxShape.circle,
            ),
            child: Center(
              child: Text(
                '$number',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 4),
                Text(
                  description,
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Theme.of(context).textTheme.bodySmall?.color,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRequirementsCard() {
    return Card(
      elevation: 2,
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Colors.purple, Colors.deepPurple],
                    ),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(Icons.checklist, color: Colors.white, size: 20),
                ),
                SizedBox(width: 12),
                Text(
                  '系统要求',
                  style: Theme.of(
                    context,
                  ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
                ),
              ],
            ),
            SizedBox(height: 16),
            _buildRequirement('Python 3.6+', '支持的 Python 版本'),
            _buildRequirement('Nuitka', '最新版本的 Nuitka 编译器'),
            _buildRequirement('C++ 编译器', 'Visual Studio Build Tools 或 MinGW'),
            _buildRequirement('Windows 10+', '支持的操作系统版本'),
          ],
        ),
      ),
    );
  }

  Widget _buildRequirement(String title, String description) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Icon(Icons.check_circle, color: Colors.green, size: 16),
          SizedBox(width: 8),
          Expanded(
            child: RichText(
              text: TextSpan(
                style: Theme.of(context).textTheme.bodyMedium,
                children: [
                  TextSpan(
                    text: '$title: ',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  TextSpan(text: description),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildParametersTab() {
    return SingleChildScrollView(
      padding: EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildParameterSection('基本参数', [
            ParameterInfo(
              '--main',
              '指定主 Python 文件',
              '必需参数，指定要编译的主 Python 文件路径',
            ),
            ParameterInfo('--output-dir', '输出目录', '指定编译后文件的输出目录'),
            ParameterInfo('--output-filename', '输出文件名', '指定生成的可执行文件名称'),
          ]),
          SizedBox(height: 16),
          _buildParameterSection('构建模式', [
            ParameterInfo('--standalone', '独立模式', '创建包含所有依赖的独立可执行文件'),
            ParameterInfo('--onefile', '单文件模式', '将所有内容打包到单个可执行文件中'),
            ParameterInfo('--module', '模块模式', '编译为 Python 扩展模块'),
          ]),
          SizedBox(height: 16),
          _buildParameterSection('优化选项', [
            ParameterInfo('--lto=yes', '链接时优化', '启用链接时优化以提高性能'),
            ParameterInfo('--enable-plugin=numpy', 'NumPy 插件', '启用 NumPy 支持插件'),
            ParameterInfo('--disable-console', '禁用控制台', '创建无控制台窗口的 GUI 应用'),
            ParameterInfo('--remove-output', '清理输出', '构建前清理输出目录'),
          ]),
          SizedBox(height: 16),
          _buildParameterSection('依赖管理', [
            ParameterInfo('--include-package', '包含包', '强制包含指定的 Python 包'),
            ParameterInfo('--include-module', '包含模块', '强制包含指定的 Python 模块'),
            ParameterInfo('--exclude-package', '排除包', '排除指定的 Python 包'),
            ParameterInfo('--include-data-files', '包含数据文件', '包含额外的数据文件'),
          ]),
        ],
      ),
    );
  }

  Widget _buildParameterSection(String title, List<ParameterInfo> parameters) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 12),
            ...parameters.map((param) => _buildParameterItem(param)).toList(),
          ],
        ),
      ),
    );
  }

  Widget _buildParameterItem(ParameterInfo param) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(4),
                  border: Border.all(
                    color: Theme.of(context).primaryColor.withOpacity(0.3),
                  ),
                ),
                child: Text(
                  param.parameter,
                  style: TextStyle(
                    fontFamily: 'monospace',
                    fontWeight: FontWeight.bold,
                    color: Theme.of(context).primaryColor,
                  ),
                ),
              ),
              SizedBox(width: 8),
              Expanded(
                child: Text(
                  param.name,
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              IconButton(
                icon: Icon(Icons.copy, size: 16),
                onPressed: () => _copyToClipboard(param.parameter),
                tooltip: '复制参数',
              ),
            ],
          ),
          SizedBox(height: 4),
          Padding(
            padding: EdgeInsets.only(left: 8),
            child: Text(
              param.description,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).textTheme.bodySmall?.color,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildExamplesTab() {
    return SingleChildScrollView(
      padding: EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildExampleCard(
            '基本 GUI 应用',
            '编译一个简单的 GUI 应用程序',
            'nuitka --standalone --disable-console --output-dir=dist main.py',
            '适用于使用 tkinter、PyQt 或其他 GUI 框架的应用程序',
          ),
          SizedBox(height: 16),
          _buildExampleCard(
            '控制台应用',
            '编译命令行工具或脚本',
            'nuitka --standalone --output-dir=dist --output-filename=mytool.exe main.py',
            '适用于命令行工具、批处理脚本等控制台应用',
          ),
          SizedBox(height: 16),
          _buildExampleCard(
            'NumPy/SciPy 应用',
            '编译使用科学计算库的应用',
            'nuitka --standalone --enable-plugin=numpy --include-package=scipy --output-dir=dist main.py',
            '适用于数据分析、机器学习等科学计算应用',
          ),
          SizedBox(height: 16),
          _buildExampleCard(
            '单文件应用',
            '创建单个可执行文件',
            'nuitka --onefile --disable-console --output-dir=dist main.py',
            '生成单个 .exe 文件，便于分发，但启动速度较慢',
          ),
          SizedBox(height: 16),
          _buildExampleCard(
            'Web 应用 (Flask)',
            '编译 Flask Web 应用',
            'nuitka --standalone --include-package=flask --include-data-files=templates=templates --output-dir=dist app.py',
            '包含模板文件和静态资源的 Web 应用程序',
          ),
        ],
      ),
    );
  }

  Widget _buildExampleCard(
    String title,
    String subtitle,
    String command,
    String description,
  ) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Colors.teal, Colors.cyan],
                    ),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(Icons.code, color: Colors.white, size: 20),
                ),
                SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        title,
                        style: Theme.of(context).textTheme.titleMedium
                            ?.copyWith(fontWeight: FontWeight.bold),
                      ),
                      Text(
                        subtitle,
                        style: Theme.of(context).textTheme.bodySmall,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 12),
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.surface,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Theme.of(context).dividerColor),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      command,
                      style: TextStyle(fontFamily: 'monospace', fontSize: 12),
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.copy, size: 16),
                    onPressed: () => _copyToClipboard(command),
                    tooltip: '复制命令',
                  ),
                ],
              ),
            ),
            SizedBox(height: 8),
            Text(
              description,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).textTheme.bodySmall?.color,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBestPracticesTab() {
    return SingleChildScrollView(
      padding: EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildPracticeCard('性能优化', Icons.speed, Colors.green, [
            '使用 --lto=yes 启用链接时优化',
            '对于大型应用，考虑使用 --standalone 而非 --onefile',
            '移除不必要的依赖和模块',
            '使用适当的优化级别',
          ]),
          SizedBox(height: 16),
          _buildPracticeCard('依赖管理', Icons.account_tree, Colors.blue, [
            '使用虚拟环境隔离项目依赖',
            '明确指定需要包含的包和模块',
            '测试不同的插件组合',
            '检查生成的可执行文件大小',
          ]),
          SizedBox(height: 16),
          _buildPracticeCard('调试技巧', Icons.bug_report, Colors.orange, [
            '首先使用 --standalone 模式测试',
            '检查 Nuitka 的详细输出日志',
            '使用 --show-progress 查看编译进度',
            '在目标机器上测试可执行文件',
          ]),
          SizedBox(height: 16),
          _buildPracticeCard('分发建议', Icons.share, Colors.purple, [
            '包含必要的 DLL 文件',
            '提供安装说明和系统要求',
            '考虑使用安装程序打包',
            '测试在不同 Windows 版本上的兼容性',
          ]),
        ],
      ),
    );
  }

  Widget _buildPracticeCard(
    String title,
    IconData icon,
    Color color,
    List<String> practices,
  ) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: color,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(icon, color: Colors.white, size: 20),
                ),
                SizedBox(width: 12),
                Text(
                  title,
                  style: Theme.of(
                    context,
                  ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
                ),
              ],
            ),
            SizedBox(height: 12),
            ...practices
                .map(
                  (practice) => Padding(
                    padding: EdgeInsets.symmetric(vertical: 4),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: 6),
                          width: 6,
                          height: 6,
                          decoration: BoxDecoration(
                            color: color,
                            shape: BoxShape.circle,
                          ),
                        ),
                        SizedBox(width: 12),
                        Expanded(
                          child: Text(
                            practice,
                            style: Theme.of(context).textTheme.bodyMedium,
                          ),
                        ),
                      ],
                    ),
                  ),
                )
                .toList(),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionCard(
    String title,
    String content,
    IconData icon,
    Color color,
  ) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: color,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(icon, color: Colors.white, size: 20),
                ),
                SizedBox(width: 12),
                Expanded(
                  child: Text(
                    title,
                    style: Theme.of(context).textTheme.titleLarge?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 12),
            Text(content, style: Theme.of(context).textTheme.bodyMedium),
          ],
        ),
      ),
    );
  }

  void _copyToClipboard(String text) {
    Clipboard.setData(ClipboardData(text: text));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('已复制到剪贴板'), duration: Duration(seconds: 2)),
    );
  }
}

class ParameterInfo {
  final String parameter;
  final String name;
  final String description;

  ParameterInfo(this.parameter, this.name, this.description);
}
